/**
 * Created with IntelliJ IDEA.
 * User: inester
 * Date: 27.06.12
 * Time: 14:24
 */


var addSuccessOrFail = function(form,action){
    var result = action.result;
    if (result.success==="true"){
        var treePanel = Ext.getCmp('treepanel');
        var parentNode = treePanel.getNodeById(result.parentNodeId);
        if (parentNode){
            //next string is very important for async reload. reload don't work if the children propertie is not empty
            parentNode.attributes.children = false;
            //reload branch of tree
            parentNode.reload(function(){
                parentNode.ensureVisible(function(){
                    parentNode.expand();
                    var selNode = treePanel.getNodeById(result.nodeId);
                    selNode.select();
                    showInfo(selNode);
                });
            });
        }
        var window = Ext.getCmp('addWindowId');
        if (window){
            window.close();
        }
    }
    else{
        Ext.Msg.alert('Error','Add node error. Check all fields for valid values.');
    }
}

var addBtnHandler = function(){
    var formPanel = Ext.getCmp('formAddPanelId');
    formPanel.getForm().submit({
        url : 'data/add',
        waitTitle: 'please wait...',
        waitMsg: 'wait...',
        success: addSuccessOrFail,
        failure: addSuccessOrFail
    });
}

var cancelAddFormBtnHandler = function(){
    var window = Ext.getCmp('addWindowId');
    if (window){
        window.close();
    }
}

function addNodeWindow(selNode)
{
    var selNodePath = selNode.getPath();

    var windowTitle = "Add node";

    //specific for different kind of node form panel items
    var formPanelItems;

    //check type of selected tree node
    if (selNode.id.match("Project_")){
        formPanelItems = createEmployeeFormPanel("","Employee_");
        windowTitle = "Add employee";
    }
    else if (selNode.id.match("Department_")){
        formPanelItems = createCommonFormPanel("","Project_");
        windowTitle = "Add project";
    }
    else if (selNode.id == organizationName){
        formPanelItems = createCommonFormPanel("","Department_");
        windowTitle = "Add department";
    }

    var formButtons = [
        {
            xtype:'button',
            text:'Save',
            handler:addBtnHandler
        },
        {
            xtype:'button',
            text:'Cancel',
            handler:cancelAddFormBtnHandler
        }
    ];
    //create form panel
    var infoForm = new Ext.form.FormPanel({
        id          : 'formAddPanelId',
        name        : 'formAddPanelId',
        items		: formPanelItems,
        border      : false,
        buttons     : formButtons,
        buttonAlign : 'left',
        autoHeight: true,
        defaults    : {
            msgTarget: 'side'
        }
    });

    //add hidden fields
    var parentNodeId = new Ext.form.Hidden ({
        name:'parentNodeId',
        value:selNode.id
    });
    infoForm.add(parentNodeId);

    //create add window
    var window = Ext.getCmp('addWindowId');
    if (!window){
        window = new Ext.Window({
            id : 'addWindowId',
            title: windowTitle,
            width: 700,
            layout: 'fit',
            autoHeight: true,
            items  : {
                xtype : 'panel',
                id : 'addWindowPanelId',
                frame : true,
                autoHeight : true,
                border : false
            }
        });
    }
    else {
        window.close();
    }
    //get panel into add window
    var panelToAddForm = Ext.getCmp('addWindowPanelId');
    panelToAddForm.removeAll();
    panelToAddForm.add(infoForm);
    panelToAddForm.doLayout();

    //show window with add form
    window.show();
};

var deleteSuccessOrFail = function(response,opts){
    var mainViewport = Ext.getCmp('mainViewportId');
    mainViewport.el.unmask();
    var treePanel =  Ext.getCmp('treepanel');
    var selNode = treePanel.getSelectionModel().getSelectedNode();
    var parentNode = selNode.parentNode;
    var responseJson = Ext.decode(response.responseText);
    if (responseJson.success==="true"){
        selNode.remove();
        selNode = parentNode;
        var selNodePath = selNode.getPath();
        treePanel.expandPath(selNodePath);
        treePanel.selectPath(selNodePath);
        showInfo(selNode);
    }
    else {
        Ext.Msg.alert('Error','An error occured with the server.');
    }
}

var onConfirmDelete = function(btn){
    if (btn == 'yes') {
        var mainViewport = Ext.getCmp('mainViewportId');
        mainViewport.el.mask('Deleting...', 'x-mask-loading');
        var treePanel =  Ext.getCmp('treepanel');
        var selNode = treePanel.getSelectionModel().getSelectedNode();
        Ext.Ajax.request({
            url    : 'data/delete',
            params : {
                nodeId : selNode.id
            },
            success : deleteSuccessOrFail,
            failure : deleteSuccessOrFail
        });
    }
}
